# -*- coding: utf-8 -*-
#===================================================
# @Time : 2021/3/25 23:16                           
# @Author : weni09                                  
# @File : token.py
#===================================================
from admin.fastapi_admin.schemas import LoginIn
from datetime import datetime,timedelta
from admin.fastapi_admin.common import  pwd_context
import setting
import jwt

class Token:
    DEFAULT_CONFIG = {
        'SECRET_KEY' :'qwertyotrwoptow6786454@434',
        'ALGORITHM' : 'HS256',
        'ACCESS_TOKEN_EXPIRE_TIME': timedelta(hours=1),
        'REFRESH_TOKEN_EXPIRE_TIME': timedelta(hours=2)
    }

    expires_delta = getattr(setting, 'ACCESS_TOKEN_EXPIRE_TIME', DEFAULT_CONFIG.get('ACCESS_TOKEN_EXPIRE_TIME'))
    refresh_expires_delta = getattr(setting, 'REFRESH_TOKEN_EXPIRE_TIME', DEFAULT_CONFIG.get('REFRESH_TOKEN_EXPIRE_TIME'))
    secret_key = getattr(setting, 'SECRET_KEY', DEFAULT_CONFIG.get('SECRET_KEY'))
    algorithm = getattr(setting, 'ALGORITHM', DEFAULT_CONFIG.get('ALGORITHM'))

    def create_access_token(self,data:dict):
        to_encode = data.copy()
        expire = datetime.utcnow() + self.expires_delta
        refresh_expire = datetime.utcnow() + self.refresh_expires_delta
        iat = datetime.utcnow()
        to_encode.update(exp=expire,iat=iat)
        refresh_to_encode = to_encode.copy()
        refresh_to_encode.update(exp=refresh_expire,refresh=1)
        encoded_jwt = jwt.encode(to_encode, self.secret_key, algorithm=self.algorithm)
        refresh_encoded_jwt = jwt.encode(refresh_to_encode, self.secret_key, algorithm=self.algorithm)
        return encoded_jwt,refresh_encoded_jwt

    @staticmethod
    def get_password_hash(password):
        return pwd_context.hash(password)

    @staticmethod
    def verify_password(plain_password, hashed_password):
        return pwd_context.verify(plain_password,hashed_password)

    def authenticate_user(self,user_obj,login_in:LoginIn):
        if not user_obj:
            return False
        print(login_in.password,user_obj.password)
        if not self.verify_password(login_in.password,user_obj.password):
            return False
        return {
            'user':{
                    'username':user_obj.username,
                    "nickname":user_obj.nickname,
                    "is_superuser": user_obj.is_superuser,
                    "avatar": user_obj.avatar if hasattr(user_obj, "avatar") else None,
            },
            'user_id': user_obj.pk,
        }


token=Token()


